package com.example.qqlaobing.Umoney.view.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.example.qqlaobing.Umoney.BuildConfig;
import com.example.qqlaobing.Umoney.R;
import com.example.qqlaobing.Umoney.been.UserInfoBeen;
import com.example.qqlaobing.Umoney.net.NetRequestBusinessDefine;
import com.example.qqlaobing.Umoney.presenter.presenterImpl.HomePresenterImpl;
import com.example.qqlaobing.Umoney.presenter.presenterImpl.LoginPresenterImpl;
import com.example.qqlaobing.Umoney.presenter.presenterImpl.RegisterPresenterImpl;
import com.example.qqlaobing.Umoney.utils.MyTimerText;
import com.example.qqlaobing.Umoney.view.fragment.bean.loginBean;
import com.example.qqlaobing.Umoney.view.myview.LoadingDialog;
import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author zlz
 */
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
    @BindView(R.id.tv_line)
    TextView tvLine;
    @BindView(R.id.ll_change)
    LinearLayout llChange;
    @BindView(R.id.tv_change_password)
    TextView tvChangePassword;
    @BindView(R.id.tv_change_line)
    TextView tvChangeLine;
    @BindView(R.id.tv_password)
    TextView tvPassword;
    @BindView(R.id.rl_duanxin)
    RelativeLayout rlDuanxin;
    private Button btnLogin, btn_login_code;
    private EditText etPassword, etUsername, et_validatecode;
    private MyTimerText btnGetCode;
    private TextView tvRegiste, tv_error;
    private boolean iscode = true;
    private UserInfoBeen userInfoBeen;
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (null == msg) {
                return;
            }
            switch (msg.what) {
                case NetRequestBusinessDefine.K_LOGIN:
                    try {
                        if (msg.arg1 == 404) {
                            dialog.close();
                            return;
                        }
                        JSONObject response = (JSONObject) msg.obj;
                        String resultCode = response.getString("status");
                        if (resultCode.equals("1")) {
                            Gson gson = new Gson();
                            loginBean bean = gson.fromJson(response.toString(), loginBean.class);
                            JSONObject results = response.getJSONObject("data");
                            JSONObject member = results.getJSONObject("member");
                            NetRequestBusinessDefine.K_TOKEN = member.getString("token");
                            NetRequestBusinessDefine.login = true;
                            SharedPreferences sharedPreferences = getSharedPreferences("umoney", Context.MODE_PRIVATE); //私有数据
                            SharedPreferences.Editor editor = sharedPreferences.edit();//获取编辑器
                            editor.putString("username", etUsername.getText().toString());
                            editor.putString("qy_url", bean.getData().getMember().getQy_url());
                            Log.e("aa","---------------登录===="+response.toString());
                            editor.putString("contact_url",bean.getData().getMember().getContact_url());
                            editor.putString("token", NetRequestBusinessDefine.K_TOKEN);
                            editor.putString("xieyi", "1");
                            editor.commit();//提交修改
                            HomePresenterImpl homePresenter = new HomePresenterImpl(mHandler);
                            homePresenter.getData();

                        } else {
                            dialog.close();
                            Toast.makeText(LoginActivity.this, response.getString("msg"), Toast.LENGTH_LONG).show();

                        }
                    } catch (JSONException e) {
                        dialog.close();
                        e.printStackTrace();
                    }
                    break;
                case NetRequestBusinessDefine.K_HOME:
                    try {
                        if (msg.arg1 == 404) {
                            dialog.close();
                            return;
                        }
                        Log.e("111", "main1");
                        JSONObject response = (JSONObject) msg.obj;
                        String resultCode = response.getString("status");
                        if (resultCode.equals("1")) {
                           /* startActivity(new Intent(LoginActivity.this,CertificationCenterActivity.class));
                            LoginActivity.this.finish();*/
                            JSONObject results = response.getJSONObject("data");
                            JSONObject data = results.getJSONObject("data");
                            if (!data.getString("loan").equals("null")) {
                                dialog.close();
                                NetRequestBusinessDefine.loan = true;
                                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                                finish();
                            } else {
                                dialog.close();
                                NetRequestBusinessDefine.loan = false;
                                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                NetRequestBusinessDefine.login = true;
                                startActivity(intent);
                                finish();
                            }
                        } else {
                            dialog.close();
                            Toast.makeText(LoginActivity.this, response.getString("msg"), Toast.LENGTH_LONG).show();
                        }
                    } catch (JSONException e) {
                        dialog.close();
                        e.printStackTrace();
                    }
                    break;
                case NetRequestBusinessDefine.K_UPDATA:
                    try {
                        if (msg.arg1 == 404) {
                            dialog.close();
                            return;
                        }
                        JSONObject response = (JSONObject) msg.obj;
                        String resultCode = response.getString("status");
                        Log.e("eeeeeeeee", resultCode);
                        if (resultCode.equals("1")) {
                            int versionCode = BuildConfig.VERSION_CODE;
                            Log.e("versionCode", versionCode + "");
                            JSONObject results = response.getJSONObject("data");
                            JSONObject data = results.getJSONObject("data");
                            if (versionCode < data.getInt("code")) {
                                dialog.close();
                                Log.e("url", data.getString("app_link"));
                                upData(data.getString("app_link"));
                            } else {
                                if (iscode) {//验证码登陆
                                    LoginPresenterImpl loginPresenter = new LoginPresenterImpl(mHandler);
                                    loginPresenter.codeLogain(etUsername.getText().toString(), et_validatecode.getText().toString(), address);
                                } else {//密码登陆
                                    LoginPresenterImpl loginPresenter = new LoginPresenterImpl(mHandler, etUsername.getText().toString(), etPassword.getText().toString(), address, getPackageName());
                                    loginPresenter.postData();
                                }

                            }

                        }
                    } catch (JSONException e) {
                        dialog.close();
                        e.printStackTrace();
                    }
                    break;
                case NetRequestBusinessDefine.K_GETS:
                    if (dialog != null) {
                        dialog.close();
                    }
                    try {
                        if (msg.arg1 == 404) {
                            return;
                        }
                        Log.e("net", msg.obj.toString());
                        JSONObject response = (JSONObject) msg.obj;
                        String resultCode = response.getString("status");
                        if (resultCode.equals("1")) {
                            if (!response.isNull("data")) {
                                btnGetCode.start();
                                Toast.makeText(LoginActivity.this, "验证码发送成功", Toast.LENGTH_LONG).show();
                            }
                        } else {
                            Toast.makeText(LoginActivity.this, response.getString("msg"), Toast.LENGTH_LONG).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case NetRequestBusinessDefine.K_LOGIN_CODE:
                    if (dialog != null) {
                        dialog.close();
                    }
                    try {
                        if (msg.arg1 == 404) {
                            return;
                        }
                        Log.e("net", msg.obj.toString());
                        JSONObject response = (JSONObject) msg.obj;
                        String resultCode = response.getString("status");
                        if (resultCode.equals("1")) {
                            JSONObject results = response.getJSONObject("data");
                            JSONObject member = results.getJSONObject("member");
                            NetRequestBusinessDefine.K_TOKEN = member.getString("token");
                            Gson gson = new Gson();
                            loginBean bean = gson.fromJson(response.toString(), loginBean.class);
                            NetRequestBusinessDefine.login = true;
                            SharedPreferences sharedPreferences = getSharedPreferences("umoney", Context.MODE_PRIVATE); //私有数据
                            SharedPreferences.Editor editor = sharedPreferences.edit();//获取编辑器
                            editor.putString("username", etUsername.getText().toString());
                            editor.putString("token", NetRequestBusinessDefine.K_TOKEN);
                            editor.putString("contact_url",bean.getData().getMember().getContact_url());
                            editor.putString("qy_url", bean.getData().getMember().getQy_url());
                            editor.commit();//提交修改
                            HomePresenterImpl homePresenter = new HomePresenterImpl(mHandler);
                            homePresenter.getData();
                        } else {
                            Toast.makeText(LoginActivity.this, response.getString("msg"), Toast.LENGTH_LONG).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    break;
            }
        }
    };
    private LoadingDialog dialog;
    private String address = "";
    private int tpye = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_login);
        ImmersionBar.with(this).init();
        ImmersionBar.with(this).statusBarDarkFont(true).init();
        ButterKnife.bind(this);
        share = getSharedPreferences("umoney", Activity.MODE_PRIVATE);
        if (!share.getString("token", "").equals("")) {
            NetRequestBusinessDefine.K_TOKEN = share.getString("token", "");
            NetRequestBusinessDefine.loan = true;
            startActivity(new Intent(LoginActivity.this, MainActivity.class));
            finish();
            return;
        }
        test();
        initview();
        initData();
    }

    public static boolean LoginActivityStatus = false;
    SharedPreferences share;

    private void initData() {
        LoginActivityStatus = true;
        btnLogin.setOnClickListener(this);
        tvRegiste.setOnClickListener(this);
        tv_error.setOnClickListener(this);
        btnGetCode.setOnClickListener(this);
        tvChangePassword.setOnClickListener(this);
        tvPassword.setOnClickListener(this);
        btnLogin.getBackground().setAlpha(200);
        if (share != null) {
            etUsername.setText(share.getString("username", ""));
        }
        iscode = true;
        tvChangeLine.setVisibility(View.VISIBLE);
        tvLine.setVisibility(View.GONE);
        tvChangePassword.setSelected(true);
        tvPassword.setSelected(false);
        llChange.setVisibility(View.VISIBLE);
        etPassword.setVisibility(View.GONE);
    }

    private void initview() {
        btnLogin = (Button) findViewById(R.id.btn_login);
        etPassword = (EditText) findViewById(R.id.et_password);
        etUsername = (EditText) findViewById(R.id.et_username);
        et_validatecode = (EditText) findViewById(R.id.et_validatecode);
        tvRegiste = (TextView) findViewById(R.id.tv_registe);
        tv_error = (TextView) findViewById(R.id.tv_error);
        btnGetCode = (MyTimerText) findViewById(R.id.btn_getcode);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_login:
                if (etUsername.getText().toString().equals("")) {
                    Toast.makeText(LoginActivity.this, "请输入用户名", Toast.LENGTH_SHORT).show();
                } else {
                    dialog = new LoadingDialog(this, "玩命加载中...");
                    dialog.show();
                    LoginPresenterImpl presenter = new LoginPresenterImpl(mHandler);
                    presenter.getData();
                }
                break;
            case R.id.btn_getcode://获取验证码
                if (etUsername.getText().toString().length() == 11) {
                    //验证码接口
                    dialog = new LoadingDialog(this, "玩命加载中...");
                    dialog.show();
                    RegisterPresenterImpl presenter = new RegisterPresenterImpl(mHandler, etUsername.getText().toString(), "2");
                    presenter.getData();
                } else {
                    Toast.makeText(LoginActivity.this, "请输入正确手机号", Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.tv_change_password://短信验证码登录
                iscode = true;
                tvChangeLine.setVisibility(View.VISIBLE);
                tvLine.setVisibility(View.GONE);
                tvChangePassword.setSelected(true);
                tvPassword.setSelected(false);
                llChange.setVisibility(View.VISIBLE);
                etPassword.setVisibility(View.GONE);
                break;
            case R.id.tv_password://密码登录
                iscode = false;
                tvChangeLine.setVisibility(View.GONE);
                tvLine.setVisibility(View.VISIBLE);
                tvChangePassword.setSelected(false);
                tvPassword.setSelected(true);
                llChange.setVisibility(View.GONE);
                etPassword.setVisibility(View.VISIBLE);
                break;
            case R.id.tv_registe:
                startActivity(new Intent(LoginActivity.this, RegisteActivity.class));
                break;
            case R.id.tv_error:
                startActivity(new Intent(LoginActivity.this, FindPasswordActivity.class));
                break;
            default:
                break;
        }
    }

    public void upData(final String url) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("更新提示");
        builder.setMessage("退出");
        builder.setNegativeButton("退出软件", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                LoginActivity.this.finish();
            }
        });
        builder.setPositiveButton("开始更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                Uri content_url = Uri.parse(url);
                intent.setData(content_url);
                startActivity(intent);
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    @Override
    protected void onDestroy() {
        Log.e("destroy", "destroy");
        super.onDestroy();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    public void test() {
        // 要申请的权限 数组 可以同时申请多个权限
        String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};

        if (Build.VERSION.SDK_INT >= 23) {
            //如果超过6.0才需要动态权限，否则不需要动态权限
            //如果同时申请多个权限，可以for循环遍历
            for (int i = 0; i < permissions.length; i++) {
                int check = ContextCompat.checkSelfPermission(LoginActivity.this, permissions[i]);
                // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                if (check != PackageManager.PERMISSION_GRANTED) {
                    //手动去请求用户打开权限(可以在数组中添加多个权限) 1 为请求码 一般设置为final静态变量
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 321);
                }
            }

        } else {
        }
    }

    //    // 用户权限 申请 的回调方法
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 321) {

            if (grantResults.length == 3 && grantResults[0] == PackageManager.PERMISSION_GRANTED &&
                    grantResults[1] == PackageManager.PERMISSION_GRANTED && grantResults[2] == PackageManager.PERMISSION_GRANTED) {
//                getLocation();
                Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();

            } else {
                for (int i = 0; i < permissions.length; i++) {
                    // 判断用户是否 点击了不再提醒。(检测该权限是否还可以申请)
                    boolean b = shouldShowRequestPermissionRationale(permissions[i]);
                    if (!b) {
                        // 用户还是想用我的 APP 的
                        // 提示用户去应用设置界面手动开启权限
//                        showDialogTipUserGoToAppSettting();
                        Toast.makeText(this, "请前往设置打开权限", Toast.LENGTH_SHORT).show();
                    } else {
                        LoginActivity.this.finish();
                        finish();
                    }
                }
            }

        }
    }

    @OnClick(R.id.userXieyi)
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.userXieyi://用户协议
                Intent intent1 = new Intent(LoginActivity.this, AgreeWebActivity.class);
                startActivity(intent1);
                break;
        }

    }
}
